<?php
/**
 * (logic)（临时）第三方广告费
 */
namespace App\Logic\File\Profit;

use App\Models\Basics\SysCountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductSku;
use App\Models\MonthlyReport\Tmp\TmpThAds;
class ParseThAdsFile
{
    /**
     * 解析AdsFile
     * @param $lines
     * @param $date
     * @return int
     */
    public static function exeParse($lines,$date){
        $count = count($lines);
        $i = 0;
        $num = 100;
        $re_count = 0;
        while(true){
            if(empty($lines))break;
            $_lines = array_splice($lines,$i,$num);
            foreach ($_lines as $line){
                $flag = self::_addThAds($line,$date);
                $flag && $re_count++;
            }
        }
        return $re_count == $count ? 1 : 0;
    }

    private static function _addThAds($temp,$date){
        if(count($temp) < 3)return true;
        if(!$temp[0])return true;
        $country = strtoupper($temp[0]);
        $sellerSku = null;
        if(isset($temp[1]) && $temp[1]){
            $sku = ParseFile::matchSku($temp[1]);
            if($sku){
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if($pSkuId){
                    $countryId = SysCountry::getIdByCountry($country);
                    $_sellerSku = ProductAmazonSku::query()
                        ->where('psku_id',$pSkuId)
                        ->where('country_id',$countryId ?: 0)
                        ->value('seller_sku');
                    if($_sellerSku){
                        $sellerSku = $_sellerSku;
                    }
                }
            }
        }

        //第三方广告费（临时）
        $re = TmpThAds::create([
            'report_date' => $date,
            'country' => $country,
            'seller_sku' => $sellerSku,
            'spend' => replaceAmountChar($temp[2]),
        ]);
        return !$re ? false : true;
    }
}
